package com.estronger.shopmanage.ui.send;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B21SendDetail;
import com.estronger.shopmanage.bean.B21SendDetail.SendItem;
import com.estronger.shopmanage.bean.B23SendDetail;
import com.estronger.shopmanage.bean.B31BuildDetail;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.grab.activity.GrabPondActivity;
import com.estronger.shopmanage.ui.grab.bean.GrabOrderBean;
import com.estronger.shopmanage.ui.grab.presenter.GrabComPresenter;
import com.estronger.shopmanage.ui.grab.presenter.IGrabComView;
import com.estronger.shopmanage.ui.install.BuildDetailActivity;
import com.estronger.shopmanage.ui.order.activity.SelectActionActivity;
import com.estronger.shopmanage.ui.order.bean.OrderAttributeBean;
import com.estronger.shopmanage.view.AbnormalDeclareView;
import com.estronger.shopmanage.view.AppDialog;
import com.lidroid.xutils.http.RequestParams;
import com.soonfor.evaluate.tools.ComToast;
import com.soonfor.evaluate.tools.CustomDialog;
import com.soonfor.evaluate.tools.dialog.normal.NormalDialog;
import com.soonfor.evaluate.tools.dialog.normal.OnBtnClickL;
import com.soonfor.systemcodes.SystemCodes;

import java.util.ArrayList;

public class SendDetailActivity extends BaseActivity implements OnClickListener {

    private TextView tv_name, tv_phone, tv_time, tv_number, tv_address,
            tv_build_count, tv_complesh_time, tv_complesh_name,
            tv_send_stkname, tv_remark1, tv_place_desc;
    private TextView tv_goods_property, tv_goods_how_many, tv_goods_feature,
            tv_goods_name, tv_title;
    private LinearLayout ll_bill_contener, ll_place_contener,
            ll_goods_contener, ll_bottom_contener1, llfPhone;
    private View rootView, callView, smsView;
    private String dlvid, cstname;
    private ScrollView sv_root;
    public static int SEND_CALL = 10000;
    private ArrayList<String> imgArr = new ArrayList<String>();
    private GrabOrderBean.DataBean goBean;//抢单对象
    private TextView tvfButton;
    NormalDialog ndialog;

    private RelativeLayout rl_selectImageList;//选择图片上传日期
    private TextView tvUpManTitle;//上传人的标题
    Integer upManRequestCode = 101;//选择图片的code
    ArrayList<OrderAttributeBean> upManList = new ArrayList<>();
    String fsrid = "0";//上传图片选择位置的id
    B21SendDetail detailInfo;//详情

    @Override
    protected void init() {
        dlvid = getIntent().getStringExtra("dlvid");
        try {
            goBean = (GrabOrderBean.DataBean) getIntent().getSerializableExtra("isGrabOrderBean");
        } catch (Exception e) {
            goBean = null;
        }
        RequestParams params = new RequestParams();
        //送货完工接口 dlvgettaskdetail
        params.addBodyParameter("sf_action", "dlvgettaskdetail");
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("dlvid", dlvid);
        connect(params, NetManager.SEND_DETAIL);
        showDialog("获取送货详情中...", true);
    }

    @Override
    protected void initView() {
        rootView = View.inflate(this, R.layout.activity_task_detail, null);
        setContentView(rootView);
        tvfButton = findViewById(R.id.tvfButton);
        if (goBean != null) {//抢单
            tvfButton.setVisibility(View.VISIBLE);
            tvfButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    String hintText = "亲，抢单完成后请尽快与客户再次确认" + goBean.getTaskTypeDesc() + "日期，任务预期未处理，将会对您的信誉造成影响";
                    ndialog = CustomDialog.getInstance().getNormalDialog(SendDetailActivity.this, "温馨提示", hintText,
                            new OnBtnClickL() {
                                @Override
                                public void onBtnClick(View view) {
                                    ndialog.dismiss();
                                    showDialog("抢单中...", true);
                                    new GrabComPresenter(SendDetailActivity.this, new IGrabComView() {
                                        @Override
                                        public void refreshAfterGrabTask(boolean isSuccess, String msg) {
                                            if (isSuccess) {
                                                ComToast.showSuccessToast(SendDetailActivity.this, "抢单成功");
                                                GrabPondActivity.ItemPosition = 0;
                                                SendDetailActivity.this.finish();
                                            } else {
                                                ComToast.showFailToast(SendDetailActivity.this, "抢单失败");
                                            }
                                            dimssDialog();
                                        }
                                    }).grabTask(goBean.getFtaskid(), goBean.getFtasktype());
                                }
                            });
                    ndialog.show();
                }
            });
        } else {
            tvfButton.setVisibility(View.GONE);
        }
        sv_root = (ScrollView) findViewById(R.id.detail_scroller);
    }

    private void initTitle(View root) {
        tv_name = (TextView) root.findViewById(R.id.send_detail_name);
        tv_phone = (TextView) root.findViewById(R.id.send_detail_phone);
        tv_time = (TextView) root.findViewById(R.id.send_detail_appointment);
        tv_number = (TextView) root.findViewById(R.id.send_detail_number);
        tv_address = (TextView) root.findViewById(R.id.send_detail_location);
        tv_name = (TextView) root.findViewById(R.id.send_detail_name);
        tv_send_stkname = (TextView) root.findViewById(R.id.send_stkname);
        tv_build_count = (TextView) findViewById(R.id.send_count);
        tv_title = (TextView) findViewById(R.id.Send_title);
        tv_title.setText("送货任务详情");
        llfPhone = root.findViewById(R.id.llfPhone);
        if (goBean != null) {
            llfPhone.setVisibility(View.GONE);
        } else {
            llfPhone.setVisibility(View.VISIBLE);
        }
        ll_goods_contener = root.findViewById(R.id.send_goods_contener);
        callView = root.findViewById(R.id.send_detail_call);
        smsView = root.findViewById(R.id.send_detail_sms);

        callView.setOnClickListener(this);
        smsView.setOnClickListener(this);
        initBottom();
    }

    private void initBottom() {
        ll_bottom_contener1 = (LinearLayout) findViewById(R.id.buttom_contener);
        tv_remark1 = (TextView) ll_bottom_contener1.findViewById(R.id.send_remark1);
    }

    private View initCompleshView() {
        View compleshView = View.inflate(this, R.layout.send_order_detail, null);
        tv_complesh_name = (TextView) compleshView.findViewById(R.id.complesh_name);
        tv_place_desc = (TextView) compleshView.findViewById(R.id.place_desc);
        ll_goods_contener = (LinearLayout) compleshView.findViewById(R.id.send_goods_contener2);
        tv_build_count = (TextView) compleshView.findViewById(R.id.detail_count_num);
        tv_number = (TextView) compleshView.findViewById(R.id.send_detail_bill2);
        tv_complesh_time = (TextView) compleshView.findViewById(R.id.send_detail_time);

        ll_bill_contener = (LinearLayout) compleshView.findViewById(R.id.detail_all_bill_contener);
        ll_place_contener = (LinearLayout) compleshView.findViewById(R.id.detail_all_place_contener);
        // hScrollview = (HorizontalScrollView)
        // compleshView.findViewById(R.id.detail_all_bill_scroller);
        // hScrollview2 = (HorizontalScrollView)
        // compleshView.findViewById(R.id.detail_all_place_scroller);

        rl_selectImageList = (RelativeLayout) compleshView.findViewById(R.id.rlfSelectImg);
        rl_selectImageList.setOnClickListener(onClickListener);
        tvUpManTitle = compleshView.findViewById(R.id.tvfImgTitle);

        return compleshView;
    }

    private Dialog dialog;

    /*点击切换图片*/
    View.OnClickListener onClickListener = new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            SelectActionActivity.openActivity(SendDetailActivity.this, 8, upManList, fsrid, upManRequestCode);
        }
    };

    @Override
    public void onClick(View v) {
        String number = tv_phone.getText().toString();
        switch (v.getId()) {
            case R.id.send_detail_sms:
                if (isRightNumber(number)) {
                    Uri uri = Uri.parse("smsto:" + number);
                    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
                    startActivity(intent);
                }
                break;
            case R.id.send_detail_call:
                if (isRightNumber(number)) {
                    dialog = AppDialog.createDialog(this, cstname, number, this,
                            dlvid);
                    dialog.show();
                }
                break;
            case R.id.ok:
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
                        + number));
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                startActivity(intent);
                dialog.dismiss();
                break;
        }
    }

    /*处理附件信息*/
    void handleFileValue(String fsrcid) {

        /*如果启用可以选中多张图片，则可选择图片*/
        if (SystemCodes.getInstance().getDSM_IfFinishCanUpdateAttaOnly() == 1){
            rl_selectImageList.setVisibility(View.VISIBLE);
        }else {
            rl_selectImageList.setVisibility(View.GONE);
            fsrcid = "0";//设置成所有的图片都可以显示
        }
        B21SendDetail detail = detailInfo;
        if (TextUtils.isEmpty(detail.data.buildname)) {
            tv_complesh_name.setText(detail.data.cstname);
        } else {
            tv_complesh_name.setText(detail.data.buildname + "-"
                    + detail.data.cstname);
        }
        cstname = detail.data.cstname;
        tv_place_desc.setText(detail.data.dlvremark);
        tv_number.setText("送货单号:" + detail.data.dlvno);
        tv_complesh_time.setText(detail.data.rddate);
        /*先移除视图*/
        ll_bill_contener.removeAllViews();
        ll_place_contener.removeAllViews();
        if (detail.data.imgitem.size() > 0) {
            // hScrollview.setVisibility(View.VISIBLE);
            for (int i = 0; i < detail.data.imgitem.size(); i++) {
                B21SendDetail.BuildIMG buildIMG = detail.data.imgitem.get(i);
                /*不是选中的id，并且不是全部的则不显示*/
                if (!buildIMG.srcid.equals(fsrcid) && !fsrcid.equals("0")){
                    continue;
                }
                imgArr.add(detail.data.imgitem.get(i).imgpath);
                View item = View.inflate(this,
                        R.layout.img_item_big, null);
                ImageView iv = (ImageView) item
                        .findViewById(R.id.item_img);
                MyApplication.imageLoader
                        .displayImage(
                                NetManager.getDownloadURL()
                                        + "?filepath="
                                        + detail.data.imgitem
                                        .get(i).imgpath,
                                iv, MyApplication.options);
                iv.setTag(NetManager.getDownloadURL()
                        + "?filepath="
                        + detail.data.imgitem.get(i).imgpath);
                if (detail.data.imgitem.get(i).phaselv == 5) {
                    ll_bill_contener.addView(item);
                } else {
                    ll_place_contener.addView(item);
                }
            }
        }
    }

    @Override
    protected void onNetSuccess(int code, String result) {
        if (NetManager.SEND_DETAIL == code) {
            B21SendDetail detail = gson.fromJson(result, B21SendDetail.class);
            if (detail.success && detail.data != null) {
                detailInfo = detail;
                if (detail.data.revstatus == 1) { // 这里表示已经送货完成
                    // 再已送货的 状态下 设置所有已送货底部的信;
                    sv_root.addView(initCompleshView());
                    upManList.clear();
                    if (detail.data.upmanlist != null && detail.data.upmanlist.size() > 0) {
                        for (B21SendDetail.SendUpMan upMan : detail.data.upmanlist) {
                            OrderAttributeBean bean = new OrderAttributeBean();
                            bean.setAttId(upMan.fsrcid);
                            bean.setAttName(upMan.ftitle);
                            upManList.add(bean);
                        }
                        fsrid = upManList.get(0).getAttId();
                        tvUpManTitle.setText(upManList.get(0).getAttName());
                    }
                    this.handleFileValue(fsrid);
                } else {
                    // 下面表示还没送货的详情展示信息
                    View child = View.inflate(this, R.layout.send_item_detail,
                            null);
                    sv_root.addView(child);
                    initTitle(sv_root);
                    ll_bottom_contener1.setVisibility(View.VISIBLE);
                    if (TextUtils.isEmpty(detail.data.buildname)) {
                        tv_name.setText(detail.data.cstname);
                    } else {
                        tv_name.setText(detail.data.buildname + "-"
                                + detail.data.cstname);
                    }

                    tv_phone.setText(detail.data.cstmobile);
                    tv_time.setText("预约送货时间:" + detail.data.pddate);
                    tv_address.setText(detail.data.address);
                    tv_number.setText("送货单号:" + detail.data.dlvno);
                    tv_remark1.setText(detail.data.dlvremark);
                    tv_send_stkname.setText(detail.data.stkname);

                    RequestParams params = new RequestParams();
                    params.addBodyParameter("sf_action", "getdlvinfo");
                    params.addBodyParameter("usercode",
                            MyApplication.getUserCode());
                    params.addBodyParameter("dlvid", dlvid);
                    connect(params, 4444);
                }

                // 共同的货物信息
                if (detail.data.item != null) {
                    tv_build_count.setText(detail.data.item.size() + "");

                    for (int i = 0; i < detail.data.item.size(); i++) {
                        SendItem item = detail.data.item.get(i);
                        View view = View.inflate(this, R.layout.goods_item,
                                null);

                        ImageView goods_img = (ImageView) view
                                .findViewById(R.id.goods_item_img);
                        tv_goods_name = (TextView) view
                                .findViewById(R.id.goods_name);
                        tv_goods_property = (TextView) view
                                .findViewById(R.id.goods_property);
                        tv_goods_how_many = (TextView) view
                                .findViewById(R.id.goods_count);
                        tv_goods_feature = (TextView) view
                                .findViewById(R.id.goods_feature);
                        if (!TextUtils.isEmpty(item.simplepicfile)) {
                            String path = NetManager.getDownloadURL()
                                    + "?filepath=" + item.simplepicfile;
                            goods_img.setTag(path);
                            MyApplication.imageLoader.displayImage(path,
                                    goods_img, MyApplication.options);
                        }
                        tv_goods_name.setText(item.goodsname);
                        tv_goods_property.setText(item.sizedesc);
                        tv_goods_how_many.setText(item.qty + "");
                        tv_goods_feature.setText(item.unitname);
                        ll_goods_contener.addView(view);
                    }
                }

            }
        }
        super.onNetSuccess(code, result);

        if (4444 == code) {
            B23SendDetail detail = gson.fromJson(result, B23SendDetail.class);
            if (detail.success && detail.data != null) {
                tv_remark1.setText(detail.data.remark);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == upManRequestCode){
            if (data != null) {
                OrderAttributeBean attributeBean = (OrderAttributeBean) data.getParcelableExtra(AbnormalDeclareView.BIND_DATA);
                fsrid = attributeBean.getAttId();
                tvUpManTitle.setText(attributeBean.getAttName());
                handleFileValue(fsrid);
            }
        }
    }

    @Override
    protected void onNetErorr(int code, String result) {
        super.onNetErorr(code, result);
    }

    public void viewPhoto(View view) {
        viewGoods(view);
    }

    public void viewGoods(View view) {
        showGoodsPop(view.getTag().toString());
    }

    private PopupWindow sharedPop;

    public void showGoodsPop(String url) {

        if (sharedPop == null) {
            View contentView = View.inflate(this, R.layout.shared_pop_window,
                    null);
            sharedPop = new PopupWindow(contentView, LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT, true);
            sharedPop.setAnimationStyle(R.style.goods_pop);
            sharedPop.setBackgroundDrawable(new BitmapDrawable());
            sharedPop.setFocusable(true);
        }
        ImageView iv = (ImageView) sharedPop.getContentView().findViewById(
                R.id.goods_img_big);
        iv.setImageResource(R.drawable.goods_default);
        // iv.setImageBitmap(BitmapFactory.decodeFile(url));
        MyApplication.imageLoader.displayImage(url, iv, MyApplication.options);
        sharedPop.showAtLocation(rootView, Gravity.CENTER, 0, 0);
    }

    @Override
    public void onBackPressed() {
        if (null != sharedPop && sharedPop.isShowing()) {
            sharedPop.dismiss();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        if (sharedPop != null && sharedPop.isShowing()) {
            sharedPop.dismiss();
        }
        super.onDestroy();
    }

    public void closeGoodsPop(View view) {
        sharedPop.dismiss();
    }

}
